package bluetooth;

import components.SysTray;
import java.io.DataInputStream;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import util.MyCmdParser;



/**
 * 蓝牙服务类
 * @author cccssw
 * 
 */
public class BlueService implements Runnable {
    //服务标示符
    private final static UUID SERVER_UUID = new UUID("F0E0D0C0B0A000908070605040302010", false);
    //流连接通知器
    private StreamConnectionNotifier notifier;
    /** 本地设备管理类 */
    private LocalDevice localDevice = null;
    //服务记录
    ServiceRecord serviceRecord;
    

    public BlueService() {
    }

    /**
     * 开启服务
     */
    public void startService() {
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            notifier = (StreamConnectionNotifier) Connector.open(getConnectionStr());

            serviceRecord = localDevice.getRecord(notifier);
        } catch (Exception ex) {
            System.out.println("occur exception here: " + ex.getMessage());
        }

        while (true) {
            StreamConnection conn = null;
            try {
                conn = notifier.acceptAndOpen();
            } catch (Exception ex) {
                System.out.println("occur exception when accept connection~");
                continue;
            }

            //开启对连接的处理线程
            new Thread(new ProcessConnection(conn)).start();
        }
    }

    /**
     * 获取连接字符串
     * @return
     */
    private String getConnectionStr() {
        StringBuilder sb = new StringBuilder("btspp://");
        sb.append("localhost").append(":");
        sb.append(SERVER_UUID.toString());
        sb.append(";name=BlueMessage");
        sb.append(";authorize=false");
        return sb.toString();
    }

    /**
     * 蓝牙初始化
     * @return
     */
    public boolean initialBluetooth() {
        boolean btReady = true;
        System.out.println("initializing bluetooth");
        try {
            localDevice = LocalDevice.getLocalDevice();
            if (!localDevice.setDiscoverable(DiscoveryAgent.GIAC)) {
                btReady = false;
            }
        } catch (Exception e) {
            btReady = false;
        }

        return btReady;
    }

    /**
     * 处理客户端连接的线程
     * @author cccssw
     * 
     */
    private class ProcessConnection implements Runnable {
        //连接流

        private StreamConnection conn = null;
        //读取流中
        private DataInputStream dis = null;


        public ProcessConnection(StreamConnection conn) {
            this.conn = conn;
        }

        @Override
        public void run() {
            System.out.println("client connected...");

            try {
                dis = conn.openDataInputStream();
                SysTray.onService="in";
                SysTray.freshIcon();
                
                while (true) {
                    String code = readInputString();

                    System.out.println("receive code: " + code);

                    analysis(code);
                }

            } catch (Exception ex) {

                System.out.println("occur exception ,message is " + ex.getMessage());
            }
        }

        private  void analysis(String code) {
            System.out.println("analysis code:"+code);//testing
            if(code=="Close_conn"||code==null){
                SysTray.onService="out";
                SysTray.freshIcon(); 
                if(code==null){
                    MyCmdParser.ParseCommand(code); 
                }
            }else{
               MyCmdParser.ParseCommand(code); 
            }
            
            
        }

        /**
         * 读取接受的数据
         * @param conn
         * @return
         */
        private String readInputString() {
            try {
                String msg = dis.readUTF();

                return msg;
            } catch (Exception ex) {
                System.out.println("occur exception when read data~");
                return ex.getMessage();
            }
        }
    }
}
